from flask import Flask, request, jsonify
from flask_cors import *
from PIL import Image
import io
import time
import json
import socket
app = Flask(__name__)
CORS(app, resources=r'/*')


@app.route('/api/submit', methods=['POST'])
def submit_data():
    data = request.get_json()
    print("Received Data:", data)


    print("连接开始建立")
    # 创建一个socket对象
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 连接到节点2的IP地址和端口号
    node2_ip = "192.168.115.11"
    node2_port = 12345
    s.connect((node2_ip, node2_port))
    # 读取JSON文件内容
    print("成功和master节点建立连接")
    with open('package.json', 'r') as file:
        json_data = json.load(file)

    # 将JSON数据转换为字符串
    json_str = json.dumps(json_data)
    data = json_str.encode()
    chunk_size = 1024
    chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]
    # 逐个发送这些块
    for chunk in chunks:
        s.sendall(chunk)

    # 关闭socket连接
    s.close()

    print("\n---\n")
    print("重新与master节点建立连接，准备接收docker的ip地址")
    # 创建一个socket对象
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    node2_ip = "192.168.115.14"
    node2_port = 12345

    s.bind((node2_ip, node2_port))

    # 开始监听连接
    s.listen(1)

    # 接受来自节点1的连接
    conn, addr = s.accept()

    return_data = b''
    while True:
        data = conn.recv(1024)
        if not data:
            break
        return_data = return_data + data

    ip = return_data.decode()
    print("接收到的docker地址为")
    print(ip)

    s.close()

    # 创建一个socket对象
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 连接到节点2的IP地址和端口号
    node2_ip = ip
    node2_port = 31222
    s.connect((node2_ip, node2_port))
    print("与docker建立连接成功")
    print("用户结点将要执行的代码和图片源数据发送给计算节点")
    # 要发送的信息，包括Python代码和原数据
    message = '''
import os
from PIL import Image

def crush_image(input_image_path, output_image_path, width, height):
    image = Image.open(input_image_path)
    resized_image = image.resize((width, height), Image.LANCZOS)
    resized_image.save(output_image_path)


image = Image.open(io.BytesIO(original_data))


output_path = "picture1.png"  
image.save(output_path)
input_image_path = 'picture1.png'
output_image_path = 'newPicture.png'
width = 100
height = 100
print("开始降低图片的分辨率")
crush_image(input_image_path, output_image_path, width, height)
print("图片分辨率降低成功并保存")
'''

    # 打开照片文件
    image_path = "picture.png"  # 请替换为实际照片文件的路径
    with open(image_path, "rb") as f:
        image_data = f.read()

    sep = b'-'
    # 将信息编码为字节串并发送
    data = message.encode('utf-8') + sep + image_data
    chunk_size = 1024
    chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]
    # 逐个发送这些块
    for chunk in chunks:
        s.sendall(chunk)
    length = len(image_data)
    print(f"在发送前我的照片大小是{length}B")
    print("发送成功")

    # 关闭socket连接
    s.close()

    time.sleep(20)

    print("\n---\n")
    print("重新建立连接准备接收数据")
    # 创建一个socket对象
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 连接到节点2的IP地址和端口号
    node2_ip = ip
    node2_port = 31222
    conn = s.connect((node2_ip, node2_port))
    print("连接建立成功")
    return_data = b''
    while True:
        data = s.recv(1024)
        if not data:
            break
        return_data = return_data + data

    image = Image.open(io.BytesIO(return_data))

    output_path = "userNewPicture.png"
    image.save(output_path)
    print("压缩后的图片保存成功 任务结束")
    print(f"压缩后的图片大小为{len(return_data)}B")

    s.close()

    return jsonify({"message": "Data received successfully"}), 200


if __name__ == '__main__':
    app.run(debug=True)
